<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Pay;
use app\common\facade\Target;

class Remit extends Base
{
    protected $name = 'remit';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function getAccountAttr($value)
    {
        return get_pay_way($value);
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getStatusAttr($value)
    {
        switch ($value) {
            case 1:
                return '未支付';
            case 2:
                return '已支付';
            default:
                return '未知';
        }
    }

    public function getConfirmTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    public static function _save($param, $logs)
    {

        parent::startTrans();
        try {
            if (!isset($param['status'])) return ['code' => -1, 'msg' => '请选择审核类型'];

            $info = parent::find($param['id']);
            if ($info->isEmpty()) return ['code' => -1, 'msg' => '审核失败'];
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '此笔记录已审核，请勿重复审核！'];
            }
            if ($param['status'] == 2) {
                $msg = '通过充值申请,标识ID【' . $param['id'] . '】会员【' . $info->user->code . '】';
                Target::Account()->basics($info['uid'], $info->getData('account'), $info['amount'], '充值', '+')
                    ->createNormal();
            } else {
                $msg = '驳回充值申请,标识ID【' . $param['id'] . '】会员【' . $info->user->code . '】';
            }

            $info->status = $param['status'];
            if ($param['status'] != 2) {
                $info->reject_msg = $param['reject_msg'];
            }
            $info->admin_id = $logs['admin']->id;
            $info->admin_name = $logs['admin']->admin_name;
            $info->confirm_time = time();
            $info->save();
            Logs::adds($msg, $logs['admin']->id, $logs['admin']->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function batch($ids, $admin)
    {
        parent::startTrans();
        try {

            $infos = parent::where('status', 1)->whereIn('id', $ids)->select();
            if ($infos->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到待审核的数据，请检查！'];
            }
            $newIds = [];
            foreach ($infos as $k => $v) {
                $res = Account::_adds($v->uid, $v->getData('account'), $v->amount, '充值', '+');
                if ($res !== true) {
                    parent::rollback();
                    return ['code' => -1, 'msg' => $res];
                }
                $newIds[] = $v->id;

            }
            parent::update(['status' => 2, 'admin_id' => $admin->id, 'admin_name' => $admin->admin_name], ['id' => $newIds]);
            parent::commit();
            $msg = '批量通过充值申请,标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $admin['id'], $admin['admin_name']);
            return ['code' => 1, 'msg' => '已批量审核'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function add($param, $user, $system): array
    {
        try {
            if (!$system['remit_open']) {
                return ['code' => -1, 'msg' => '充值通道已关闭'];
            }
            $receipt_amount = $param['amount'];
            if ($param['amount'] >= $system['remit_min']) {
                $receipt_amount = $param['amount']+$system['remit_fd'];
            }
            if ($system['remit_bs']) {
                if ($param['amount'] % $system['remit_bs'] != 0) {
                    return ['code' => -1, 'msg' => '充值倍数：' . $system['remit_bs']];
                }
            }
            $account = 'balance';
            $sn = date('Ymd') . $user->id . time();

//            $receipt_amount = 0.01;
            parent::create([
                'sn'      => $sn,
                'uid'     => $user->id,
                'account' => $account,
                'amount'  => $param['amount'],
                'receipt_amount'  => $receipt_amount,
                'create_time' => time(),
            ]);
            $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/callback/RemitCallback';
            //设置参数
            $options = Pay::setDriver('WeChat')
                ->basic('购买商品', $sn, $param['amount'], $notifyUrl)
                ->setOpenId($user->openid)
                ->create('JSAPI');
            return ['code' => 1, 'data' => $options];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function remit_save($remit,$pay_way): array
    {
        $remit->status = 2;
        $remit->pay_way = $pay_way;
        $remit->pay_time = time();
        $remit->save();
        Target::Account()
            ->basics($remit->uid, 'balance', $remit->receipt_amount, '充值', '+')
            ->setMsg($remit->uid)
            ->createRecharge();
        return ['code' => 1, 'msg' => '支付成功'];
    }
}
